﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Novacode;
using KingRoad.EPM.Web.Areas.PersonnelLog.ViewModels;
using KingRoad.EPM.Web.Areas.PersonnelLog.PersonnelLogFramework.Common;
using KingRoad.EPM.PersonnelLogEntity.Model;
using Unis.Framework.Core.Utility;
using System.Collections.ObjectModel;


namespace KingRoad.EPM.Web.Areas.PersonnelLog.Controllers
{
    public class PlmSpecialtyLogController : BaseController
    {
        /// <summary>
        /// 专业监理日志列表
        /// </summary>
        /// <returns></returns>
        public ActionResult SpecialtyLogList(string pageName)
        {
            //var vm = new PlmSpecialtyLogViewModel();
            //var list = PlmSpecialtylogUIRule.GetAllPlmSpecialtylog();
            //vm.ThePlmSpecialtylogList = list;
            //return View(vm);
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            var list = PlmSpecialtylogUIRule.GetSpecialtylogForPage(ViewBag.pageNum, ViewBag.numPerPage, "Sl_RecordDate", out totalRecord, " Sl_ContractNumber in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ");
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            //return View(new PlmSpecialtyLogViewModel { ThePlmSpecialtylogList = list });
            return String.IsNullOrEmpty(pageName) ? View(new PlmSpecialtyLogViewModel { ThePlmSpecialtylogList = list }) : View(pageName, new PlmSpecialtyLogViewModel { ThePlmSpecialtylogList = list });
        }
        /// <summary>
        /// 专业监理日志添加
        /// </summary>
        /// <returns></returns>
        public ActionResult SpecialtyLogAdd(string target, string slId)
        {
            ViewBag.OperationType = target;
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.专业监理日志);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.专业监理日志;
            if (target == "add")
            {
                var vm = new PlmSpecialtyLogViewModel();
                vm.ThePlmSpecialtylog = new PlmSpecialtylogInfo();
                vm.ThePlmSpecialtylog.Sl_UserID = GetLoginUserId;
                vm.ThePlmSpecialtylog.Sl_UserName = GetLoginUserRealName;
                vm.ThePlmSpecialtylog.Sl_RecordDate = DateTime.Now;
                if (GetLoginUserOrganizeEntity.Code == "JL" && GetJLProjectSegmentInfo.Count > 0)
                    vm.ThePlmSpecialtylog.Sl_ContractNumber = GetJLProjectSegmentInfo[0].SEGMENT_CODE;
                else
                {
                    if (GetZDJLProjectSegmentInfo.Count > 0)
                        vm.ThePlmSpecialtylog.Sl_ContractNumber = GetZDJLProjectSegmentInfo[0].SEGMENT_CODE;
                }
                vm.ThePlmSpecialtylog.Sl_RecordUser = GetLoginUserRealName;
                vm.ThePlmSpecialtylog.Sl_SpecialtyPosition = GetLoginUserInfo.WorkgroupFullName;
                vm.ThePlmSpecialtylog.Sl_SupervisorName = GetLoginUserDepartmentName;
                //附件
                var assisId = GenerateRandom();
                var assisIdRet = 0;
                CreateAssistId(PlmSpecialtylogUIRule, assisId, out assisIdRet);
                ViewBag.AssisId = assisIdRet;
                return View(vm);
            }
            else
            {
                var signle = PlmSpecialtylogUIRule.GetPlmSpecialtylogInfoById(slId);
                //附件
                var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(signle.Assist_ID, "SpecialtyLog_Rules");//SpecialtyLog_Rules  BizType类型
                ViewBag.AssisId = signle.Assist_ID;
                ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
                ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));
                var vm = new PlmSpecialtyLogViewModel { ThePlmSpecialtylog = signle };
                return View(vm);
            }
        }
        /// <summary>
        /// 专业监理日志修改
        /// </summary>
        /// <returns></returns>
        public ActionResult SpecialtyLogEdit(string target, string slId)
        {
            ViewBag.OperationType = target;
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.专业监理日志);
            var signle = PlmSpecialtylogUIRule.GetPlmSpecialtylogInfoById(slId);
            //附件
            var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(signle.Assist_ID, "SpecialtyLog_Rules");//SpecialtyLog_Rules  BizType类型
            ViewBag.AssisId = signle.Assist_ID;
            ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
            ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));

            var signlesublist = PlmSpecialtylogSubUIRule.GetPlmSpecialtylogSubInfoByFId(slId);
            var signleYBsublist = PlmSpecialtylogYBSubUIRule.GetPlmSpecialtylogYBSubInfoByFId(slId);
            var vm = new PlmSpecialtyLogViewModel { ThePlmSpecialtylog = signle, ThePlmSpecialtylogSubList = signlesublist, ThePlmSpecialtylogYBSubList = signleYBsublist };
            return View(vm);
        }
        /// <summary>
        /// 专业监理日志查看
        /// </summary>
        /// <returns></returns>
        public ActionResult SpecialtyLogView(string target, string slId)
        {
            var signle = PlmSpecialtylogUIRule.GetPlmSpecialtylogInfoById(slId);
            //附件
            var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(signle.Assist_ID, "SpecialtyLog_Rules");//SpecialtyLog_Rules  BizType类型
            ViewBag.AssisId = signle.Assist_ID;
            ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
            ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));

            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.专业监理日志);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.专业监理日志;

            var signlesublist = PlmSpecialtylogSubUIRule.GetPlmSpecialtylogSubInfoByFId(slId);
            var signleYBsublist = PlmSpecialtylogYBSubUIRule.GetPlmSpecialtylogYBSubInfoByFId(slId);
            var vm = new PlmSpecialtyLogViewModel { ThePlmSpecialtylog = signle, ThePlmSpecialtylogSubList = signlesublist, ThePlmSpecialtylogYBSubList = signleYBsublist };
            return View(vm);
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        public ActionResult SpecialtyLogAddHandle(PlmSpecialtyLogViewModel vm)
        {
            if (vm == null)
            {
                return new JsonResult()
                {
                    Data = new
                    {
                        statusCode = "300",
                        message = "操作失败",
                    }
                };
            }
            dynamic jsonReturn = new ExpandoObject();
            string operation_str = string.Empty;
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                if (vm.OperationType == "add")
                {
                    operation_str = "添加";
                    vm.ThePlmSpecialtylog.Sl_ID = Guid.NewGuid().ToString();
                    var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                    vm.ThePlmSpecialtylog.Assist_ID = AssistID;

                    PlmSpecialtylogUIRule.InsertEntity(vm.ThePlmSpecialtylog);
                    //add子表信息
                    foreach (var item in vm.ThePlmSpecialtylogSubList)
                    {
                        if (item != null)
                        {
                            item.SlS_ID = Guid.NewGuid().ToString();
                            item.Sl_ID = vm.ThePlmSpecialtylog.Sl_ID;
                            var cp = PlmSpecialtylogSubUIRule.InsertEntity(item);
                        }

                    }
                    //add子表隐蔽信息
                    foreach (var item in vm.ThePlmSpecialtylogYBSubList)
                    {
                        if (item != null)
                        {
                            item.SlYS_ID = Guid.NewGuid().ToString();
                            item.Sl_ID = vm.ThePlmSpecialtylog.Sl_ID;
                            var cp = PlmSpecialtylogYBSubUIRule.InsertEntity(item);
                        }

                    }

                }
                if (vm.OperationType == "edit")
                {
                    operation_str = "更新";
                    var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                    vm.ThePlmSpecialtylog.Assist_ID = AssistID;
                    PlmSpecialtylogUIRule.UpdateEntity(vm.ThePlmSpecialtylog);
                    //删除子表信息，再添加
                    PlmSpecialtylogSubUIRule.DeleteEntity(vm.ThePlmSpecialtylog.Sl_ID);
                    foreach (var item in vm.ThePlmSpecialtylogSubList)
                    {
                        if (item != null)
                        {
                            item.SlS_ID = Guid.NewGuid().ToString();
                            item.Sl_ID = vm.ThePlmSpecialtylog.Sl_ID;
                            var cp = PlmSpecialtylogSubUIRule.InsertEntity(item);
                        }

                    }
                    //删除隐蔽子表信息，再添加
                    PlmSpecialtylogYBSubUIRule.DeleteEntity(vm.ThePlmSpecialtylog.Sl_ID);
                    foreach (var item in vm.ThePlmSpecialtylogYBSubList)
                    {
                        if (item != null)
                        {
                            item.SlYS_ID = Guid.NewGuid().ToString();
                            item.Sl_ID = vm.ThePlmSpecialtylog.Sl_ID;
                            var cp = PlmSpecialtylogYBSubUIRule.InsertEntity(item);
                        }

                    }
                }
            });
            if (isScuess)
            {
                jsonReturn = new { statusCode = "200", message = string.Format("{0}成功", operation_str), navTabId = "PersonnelLog.PlmSpecialtyLog.SpecialtyLogList", rel = "", callbackType = "closeCurrent", forwardUrl = "", confirmMsg = "" };
            }
            else
            {
                jsonReturn = new { statusCode = "300", message = string.Format("{0}失败", operation_str) };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        /// <summary>
        /// 专业监理日志导出
        /// </summary>
        /// <returns></returns>
        public ActionResult SpecialtyLogExport(string id)
        {
            var signle = PlmSpecialtylogUIRule.GetPlmSpecialtylogInfoById(id);
            var signlesub = PlmSpecialtylogSubUIRule.GetPlmSpecialtylogSubInfoByFId(id);
            var signleYBsublist = PlmSpecialtylogYBSubUIRule.GetPlmSpecialtylogYBSubInfoByFId(id);
            string fileName = "专业监理工程师日志.docx";
            var ret = ExportToWord(fileName, signle, signlesub, signleYBsublist);
            return ret;
        }
        public FileStreamResult ExportToWord(string fileName, PlmSpecialtylogInfo t, List<PlmSpecialtylogSubInfo> signlesub, List<PlmSpecialtylogYbsubInfo> signleYBsublist)
        {
            string path = Server.MapPath("~/Areas/PersonnelLog/Upload/" + fileName);
            string savePath = Server.MapPath("~/Areas/PersonnelLog/Upload/Temp/" + Guid.NewGuid().ToString() + fileName);
            using (DocX docx = DocX.Load(path))
            {
                var rex = new Regex("[0-9]+?");
                //替换主表标签
                docx.Bookmarks.ForEach(f =>
                {
                    var bookMarkName = f.Name;
                    if (rex.IsMatch(bookMarkName))
                    {
                        bookMarkName = f.Name.Substring(0, f.Name.Length - 1);
                    }

                    if (t.ContainProperty(bookMarkName))
                    {
                        var obj = Reflection.GetProperty(t, bookMarkName);
                        var value = obj ?? "";
                        var propertyType = value.GetType().FullName;
                        if (propertyType == "System.DateTime")
                            f.SetText(Convert.ToDateTime(value).ToString("yyyy年MM月dd日"));
                        else
                            f.SetText(value.ToString());
                    }
                });
                //抽检记录表
                foreach (PlmSpecialtylogSubInfo info in signlesub)
                {
                    docx.InsertDocument(base.GetSonExportInfo("专业监理工程师(抽检记录).docx", info), true);
                }
                //隐蔽工程表
                foreach (PlmSpecialtylogYbsubInfo info in signleYBsublist)
                {
                    docx.InsertDocument(base.GetSonExportInfo("专业监理工程师(隐蔽工程记录).docx", info), true);
                }
                docx.SaveAs(savePath);
            }
            fileName = HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("UTF-8"));
            FileStream file = new FileStream(savePath, FileMode.Open);
            return File(file, "application/vnd.ms-word", fileName);
        }
        public ActionResult SpecialtyLogDelete(string slId)
        {
            dynamic jsonReturn = new ExpandoObject();
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                PlmSpecialtylogUIRule.DeleteEntity(slId);
                //删除子表信息
                PlmSpecialtylogSubUIRule.DeleteEntity(slId);
                //删除隐蔽子表信息
                PlmSpecialtylogYBSubUIRule.DeleteEntity(slId);
            });
            if (isScuess)
            {
                jsonReturn = new { statusCode = "200", message = "删除成功", navTabId = "PersonnelLog.PlmSpecialtyLog.SpecialtyLogList", rel = "", callbackType = "", forwardUrl = "", confirmMsg = "" };
            }
            else
            {
                jsonReturn = new { statusCode = "300", message = "删除失败" };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public ActionResult SplitPage(PlmSpecialtyLogViewModel vm)
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return SpecialtyLogList("SpecialtyLogList");

            ViewBag.unit = Request.Form["unit"];
            ViewBag.num = Request.Form["num"];
            ViewBag.time = Request.Form["time"];
            ViewBag.code = Request.Form["code"];

            string sql = " Sl_ContractNumber in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ";
            if (ViewBag.unit != "")
                sql += " and Sl_SupervisorName like'%" + ViewBag.unit + "%' ";
            if (ViewBag.num != "")
                sql += " and Sl_SupervisionNumber like '%" + ViewBag.num + "%' ";
            if (ViewBag.code != "")
                sql += " and Sl_ContractNumber like '%" + ViewBag.code + "%' ";
            if (ViewBag.time != "")
                sql += " and Sl_RecordDate='" + ViewBag.time + "' ";


            var list = PlmSpecialtylogUIRule.GetSpecialtylogForPage(ViewBag.pageNum, ViewBag.numPerPage, "Sl_RecordDate", out totalRecord, sql);
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("SpecialtyLogList", new PlmSpecialtyLogViewModel { ThePlmSpecialtylogList = list });
        }

    }
}
